# \source-code\setting.py

import json
import os
from pathlib import Path
import sys



class Target_setting:
    """
    设置文件
    """
    file_extension = []

    def __init__(self) -> None:
        self.file_extension = []
        self._load_from_file()

    def _load_from_file(self):
        try:
            setting_file_path = resource_path("setting.json")  # 使用 resource_path
            if not os.path.exists(setting_file_path):
                self._save_to_file()
            with open(setting_file_path, "r", encoding="utf-8") as f:
                self.__dict__ = json.load(f)
        except:
            raise FileNotFoundError("setting.json not found")
        Target_setting.file_extension = self.file_extension


    def _save_to_file(self):
        setting_file_path = os.path.join(os.path.dirname(__file__), "setting.json")
        with open(setting_file_path, "w", encoding="utf-8") as f:   
            json.dump(self.__dict__, f, ensure_ascii=False, indent=4)
        Target_setting.file_extension = self.file_extension

def setting_add_file_extension(val : str) -> int:
    '''
    添加目标后缀名
    Args:
        val: val : str 后缀名

    Returns:int
        0.执行成功
        1.空字符串
        2.输入重复后缀名
    '''
    set = Target_setting()
    if val == "":
        return 1
    if val[0] == '.':
        extension = val
    else:
        extension = '.' + val
    if extension in set.file_extension:
        print("文件后缀名已存在，请勿重复添加")
        return 2
    set.file_extension.append(extension)
    set._save_to_file()
    return 0


def setting_remove_file_extension(val : str) -> int:
    '''

    Returns:
        1 : 输入为空
        2 : 输入不存在
        0 : 执行成功
    '''
    set = Target_setting()
    extension = val
    if extension == "":
        return 1
    elif extension.isdigit():
        set.file_extension.pop(extension-1)
    elif extension.isalpha():
        if "."+ extension in set.file_extension:
            set.file_extension.remove("."+ extension)
        else:
            return 2
    elif extension in set.file_extension:
        set.file_extension.remove(extension)
    else:
        return 2

    set._save_to_file()
    return 0

def setting_restor_default() -> None:
    set = Target_setting()
    set._save_to_file()

    path_history_file = os.path.join(os.path.dirname(__file__), "PathHistory.json")
    if os.path.exists(path_history_file):
        os.remove(path_history_file)

def setting_remove_path_history() -> None:
    path_history_file = os.path.join(os.path.dirname(__file__), "PathHistory.json")
    if os.path.exists(path_history_file):
        os.remove(path_history_file)
    print("已删除路径历史记录\n")

def resource_path(filename : str):
        """
        获取设置文件的绝对路径
        """
        if getattr(sys, 'frozen', False):
            # 如果是打包后的exe文件
            base_path = Path(sys.executable).parent
            return base_path / "_internal" / filename
        else:
            # 如果是直接运行py文件
            nowpath = Path(__file__).parent

        try:
            filesPath = nowpath.rglob("setting.py").__next__()
        except StopIteration:  # 找不到文件
            raise FileNotFoundError("setting.py not found")
        filesPath = filesPath.parent / filename

        print(f"{filename} = ",filesPath)
        return filesPath